package org.wwy.demo.excel.test.word;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 不好用，不好用，不好用，不好用，不好用，不好用
 * 纯文本替换，该示例主要解决XWPFRun分段的问题，不使用run.getText方法了，直接对段落进行替换
 * 但是这里会有缺陷，模板设置的格式不会生效
 */
public class Text3 {

    private static final String pattern = "\\{\\{+[a-zA-Z0-9]+\\}\\}";   // 拿到文本标签的正则表达式

    public static void main(String[] args) throws Exception {

        final String returnurl = "D:\\fof.docx";  // 结果文件
        final String templateurl = "D:\\fof_template.docx";  // 模板文件

        InputStream is = new FileInputStream(new File(templateurl));
        XWPFDocument doc = new XWPFDocument(is);

        XWPFDocument targetDoc = new XWPFDocument(doc.getPackage());

        // 替换word模板数据
        replaceAll(doc,targetDoc);

        // 保存结果文件
        try {
            File file = new File(returnurl);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fos = new FileOutputStream(returnurl);
            targetDoc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description: 替换段落
     */
    public static void replaceAll(XWPFDocument doc,XWPFDocument targetDoc) throws Exception {
        doParagraphs(doc,targetDoc); // 处理段落文字数据，包括文字和表格、图片
    }


    /**
     * 处理段落文字
     *
     * @param doc
     * @throws InvalidFormatException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void doParagraphs(XWPFDocument doc,XWPFDocument targetDoc) throws Exception {
        // 文本数据
        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("prdName","111");
        textMap.put("monthReport","222");
        textMap.put("fundDate","333");
        textMap.put("jzrq","444");
        textMap.put("jyts","555");
        textMap.put("zxfqljjz","666");
        textMap.put("dwjz","777");
        textMap.put("ljjz","888");
        textMap.put("clylljhl","999");
        textMap.put("tqjzsyl","2222");
        textMap.put("syzgyf","3333");
        textMap.put("zgyfsyl","4444");
        textMap.put("syzdyf","5555");
        textMap.put("zdyfsyl","6666");
        textMap.put("zjjcw","7777");
        textMap.put("clmc","8888");
        textMap.put("clzmc","9999");
        textMap.put("cpyxyldzsy","2345");
        textMap.put("clsygx","23456");


        /**----------------------------处理段落------------------------------------**/
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        if (paragraphList != null && paragraphList.size() > 0) {
            for (int i=0;i<paragraphList.size();i++) {
                XWPFParagraph xwpfParagraph = targetDoc.getParagraphs().get(i);
                List<XWPFRun> runs = xwpfParagraph.getRuns();
                // 清除段落所有的run，解决run文字分段问题
                for (int j = 0; j < runs.size(); j++) {
                    XWPFRun xwpfRun = runs.get(i);
                    xwpfParagraph.removeRun(j);
                }
               /* XWPFParagraph paragraph = paragraphList.get(i);
                String ptext = paragraph.getText();  // 段落文字
//                System.out.println("段落文本：" + ptext);
                if (!StringUtils.isEmpty(ptext)) {
                    if(ptext.contains("cpyxyldzsy")){
//                        System.out.println("cpyxyldzsy");
                    }
                    List<String> resList = resolver(ptext);  // 段落里面的标签
                    for (String flag : resList) {
                        String key = flag.replaceAll("\\{\\{", "").replaceAll("}}", "");
//                        System.out.println("key =" + key);
                        String label = textMap.get(key);
                        if (!StringUtils.isEmpty(label)) {
                            ptext = ptext.replace(flag, label);  // 替换段落文字;
                        }
                    }
                }*/


//                System.out.println(ptext);

            }
        }
    }


    /**
     * 解析段落，获取里面的标签
     */
    public static List<String> resolver(String line) {
        List<String> resList = new ArrayList<String>();
        try {
            Pattern patten = Pattern.compile(pattern);//编译正则表达式
            Matcher matcher = patten.matcher(line);// 指定要匹配的字符串
            while (matcher.find()) { //此处find（）每次被调用后，会偏移到下一个匹配
                String flag = matcher.group();
                resList.add(flag);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }



}


















